﻿App.addNewPage({
	id: 'game',
	url: '/Home/Game',
	title: '',
	require: [],
	init: function () {
		var $message = $('#message'),
			$overlayGame = $('#overlayGame'),
			$userList = $('.user-list'),
			$chat = $('#chat'),
			$chatparent = $chat.parent(),
			$send = $('#send'),
			$brush = $('#brush'),
			//$tools = $('#tools'),
			$overlayTools = $('#overlayTools'),
			$cancasOvelray = $('#cancasOvelray'),
			$word = $('#word'),
			$word1 = $('#word1'),
			$word2 = $('#word2'),
			$word3 = $('#word3'),
			$rigthWord = $('#rigthWord'),
			$painter = $('#painter'),
			$winner = $('#winner'),
			$progress = $('#progress'),
			$roundResult = $('.round-result'),
			$wordCountdown = $('#wordCountdown'),
			$roundCount = $('#roundCount'),
			$skipbutton = $('#skipbutton'),
			$colorPicker = $('#colorPicker'),
			$painterName = $('#painterName'),
			$imageulr = $('#imageulr'),
			$imageulrInput = $('#imageulrInput');

		//###################################################################################################

		$('.social-likes').socialLikes();

		$imageulr.mouseenter(function () {
			TweenMax.killTweensOf($imageulr);
			TweenMax.to($imageulr, 0.5, {textShadow: '0 0 15px #cccccc'});
		}).mouseleave(function () {
			TweenMax.killTweensOf($imageulr);
			TweenMax.to($imageulr, 0.5, { textShadow: 'none' });
		});

		$imageulrInput.focus(function () {
			$imageulrInput.select();
		}).mouseup(function (e) {
			e.preventDefault();
		});;

		function sendMessage() {
			if ($message.val() != '') {
				App.signalr.server({
					hub: 'gameHub',
					action: 'sendMessage',
					data: $message.val()
				}).fail(function (e) {
					console.log('logon.page.js', e);
				});
			}
			$message.val('').focus();
		}

		$send.click(sendMessage);

		$message.bind('keyup', function (e) {
			var code = e.keyCode || e.which;
			if (code == 13) {
				e.preventDefault();
				sendMessage();
				return false;
			}
			return true;
		});

		function enableChat() {
			$send.prop('disabled', false);
			$message.prop('disabled', false);
			$message.focus(function () { this.select(); });
		}

		function disableChat() {
			$send.prop('disabled', true);
			$message.prop('disabled', true);
		}

		//###################################################################################################

		var paintInst = painter({ canvas: 'canvas' });

		App.paint = paintInst;

		var range = $(":range");
		range.rangeinput({
			progress: true,
			speed: 0,
			min: 3,
			value: 6,
			step: 0.01,
			max: 20,
			change: function (e, i) {
				var size = Math.round(i);
				$brush.css({ width: size, height: size, 'margin-top': -size / 2, 'margin-left': -size / 2 });
				paintInst.setBrushSize(size);
			}
		});
		$('.range').on('change', function () {
			var size = Math.round($(this).val());
			$brush.css({ width: size, height: size, 'margin-top': -size / 2, 'margin-left': -size / 2 });
		}).data('rangeinput').setValue(6);

		var colors = ['black', 'red', 'green', 'yellow', 'blue'];
		$.each(colors, function (i, color) {
			$('#' + color).click(function () {
				paintInst.setColor(color);
				$brush.css('background-color', color);
			});
		});

		$colorPicker.colpick({
			submit: false,
			layout: 'empty',
			color: 'ffffff',
			onShow: function (colpkr) {
				var $cp = $(colpkr);
				if ($cp.is(':visible')) {
					$colorPicker.colpickHide();
					return false;
				}
				var offset = $colorPicker.offset();
				$cp.fadeIn(100);
				$cp.offset({
					top: offset.top - $cp.height() - 10,
					left: offset.left - 47
				});
				return false;
			},
			onChange: function (hsb, hex, rgb, el, bySetColor) {
				var color = '#' + hex;
				$colorPicker.css('background-color', color);
				$brush.css('background-color', color);
			},
			onHide: function (colpkr) {
				paintInst.setColor($colorPicker.css('background-color'));
				$(colpkr).fadeOut(100);
				return false;
			}
		}).click(function () {
			$brush.css('background-color', $colorPicker.css('background-color'));
		});

		$('.colpick_empty').mouseleave(function () {
			$colorPicker.colpickHide();
		});

		$('#clear').click(function () {
			paintInst.clear();
		});

		function enablePaint() {
			$overlayTools.hide();
			paintInst.readOnly(false);
			resetPaint();
			$painterName.hide();
		}

		function disablePaint() {
			$colorPicker.colpickHide();
			$overlayTools.show();
			paintInst.readOnly(true);
		}

		function resetPaint() {
			// не чистился канвас
			if (paintInst.readOnly()) {
				paintInst.readOnly(false);
				paintInst.clear();
				paintInst.readOnly(true);
			} else {
				paintInst.clear();
			}

			paintInst.setColor('black');
			paintInst.setBrushSize(6);
			$('.range').data('rangeinput').setValue(6);
			$brush.css({ width: 6, height: 6, 'margin-top': -3, 'margin-left': -3 });
			$brush.css('background-color', 'black');
		}

		disablePaint();

		//###################################################################################################

		var countdown;

		App.signalr.client({
			hub: 'gameHub',
			action: 'chooseWord',
			fn: function (r) {
				disableChat();
				App.ui.setTitle(Localization.ChooseWord);
				$word1.text(r[0]);
				$word2.text(r[1]);
				$word3.text(r[2]);
				$('#chooseWordOverlay').show().focus();
				var i = 10;
				$wordCountdown.text('0:10');
				countdown = setInterval(function () {
					i--;
					var time = '0:0' + i.toString();
					$wordCountdown.text(time);
					App.ui.setTitle(Localization.ChooseWord + ' ' + time);
					if (i == 0) {
						skipRound();
					}
				}, 1000);
			}
		});

		$skipbutton.click(function () {
			skipRound();
		});

		function skipRound() {
			clearInterval(countdown);
			$('#chooseWordOverlay').hide();
			enableChat();
			App.signalr.server({
				hub: 'gameHub',
				action: 'startRound',
				data: -1
			});
			App.ui.setTitle(Localization.GameTitle);
		}

		function sendWord(word) {
			clearInterval(countdown);
			App.signalr.server({
				hub: 'gameHub',
				action: 'startRound',
				data: word
			});
			$('#chooseWordOverlay').hide();
			$cancasOvelray.hide();
			$imageulr.hide().attr('href', '');
			$imageulrInput.hide().val('');
			enablePaint();
			disableChat();
			runProgressBar();
			App.ui.setTitle(Localization.GameTitle);
		}

		App.signalr.client({
			hub: 'gameHub',
			action: 'startTimer',
			fn: function (r) {
				resetPaint();
				runProgressBar();
				$cancasOvelray.hide();
				$imageulr.hide().attr('href', '');
				$imageulrInput.hide().val('');
				$painterName.text(r.name).show();
			}
		});

		App.signalr.client({
			hub: 'gameHub',
			action: 'firstHint',
			fn: function (w) {
				$word.text(w);
			}
		});

		App.signalr.client({
			hub: 'gameHub',
			action: 'secondHint',
			fn: function (w) {
				$word.text(w);
			}
		});

		App.signalr.client({
			hub: 'gameHub',
			action: 'stopRound',
			fn: function (r) {
				disablePaint();
				enableChat();
				$painterName.hide();
				$word.text('');
				TweenMax.killTweensOf($progress);
				$progress.removeAttr('style');
				if (r.timerOver) {
					App.alert.info(Localization.TimeIsOver);
				}
				$painter.text(r.painter);
				$rigthWord.text(r.word);
				$winner.text(r.winner);
				$roundCount.text(Localization.RoundCount.replace('{0}', r.roundCount));
				$userList.empty();
				$.each(r.users, function (i, u) {
					appendUser(u.name, u.color, u.points);
				});
				$roundResult.show();
				$cancasOvelray.show();
			}
		});

		App.signalr.client({
			hub: 'gameHub',
			action: 'imageUrl',
			fn: function (r) {
				$imageulr.attr('href', r.url).show();
				$imageulrInput.val(r.url).show().focus();
				$message.focus();
			}
		});

		App.signalr.client({
			hub: 'gameHub',
			action: 'getImage',
			fn: function (data) {

				data.imageData = paintInst.canvas.toDataURL("image/png").replace('data:image/png;base64,', '');

				App.ajax({
					type: 'POST',
					async: true,
					url: '/upload',
					data: JSON.stringify(data),
					contentType: 'application/json; charset=utf-8',
					dataType: 'json',
					success: function(r) {
						App.signalr.server({
							hub: 'gameHub',
							action: 'shareImage',
							data: r.url
						});
					}
				});
			}
		});

		function runProgressBar() {
			$progress.removeAttr('style');
			TweenMax.set($progress, { width: '100%', transition: 'none' });
			TweenMax.to($progress, 60, { width: '0%', ease: Linear.easeNone });
			TweenMax.to($progress, 1, { backgroundColor: '#FAA732', delay: 20 });
			TweenMax.to($progress, 1, { backgroundColor: '#DA314B', delay: 40 });
		}

		$word1.click(function () { sendWord(0); $word.text($word1.text()); });
		$word2.click(function () { sendWord(1); $word.text($word2.text()); });
		$word3.click(function () { sendWord(2); $word.text($word3.text()); });

		//###################################################################################################

		App.signalr.client({
			hub: 'gameHub',
			action: 'userAdded',
			fn: function (r) {
				appendUser(r.user.name, r.user.color, r.user.points);
				App.alert.info(Localization.UserAddedMessage.replace('{name}', r.user.name));
			}
		});

		App.signalr.client({
			hub: 'gameHub',
			action: 'roomFound',
			fn: function (r) {
				if (!App.isUndefined(r.users)) {
					$.each(r.users, function (i, user) {
						appendUser(user.name, user.color, user.points);
					});
				}
				App.ui.setTitle(Localization.Waiting);
			}
		});

		function appendUser(name, color, points) {
			var pattent = '<li class="uk-grid uk-grid-small"><div class="uk-width-1-10"><div class="uk-container-center" style="background-color: {color}; height: 20px; width: 20px;"></div></div><div class="uk-width-7-10"><div class="uk-text-left uk-margin-small-left">{name}</div></div><div class="uk-width-2-10">{points}</div></li>';
			$userList.append(pattent.replace('{color}', color).replace('{name}', name).replace('{points}', points));
		}

		App.signalr.client({
			hub: 'gameHub',
			action: 'startGame',
			fn: function (r) {
				$overlayGame.hide();
				enableChat();
				if (r != true) {
					$roundResult.hide();
					$cancasOvelray.show();
				}
				App.ui.setTitle(Localization.GameTitle);
			}
		});

		App.signalr.client({
			hub: 'gameHub',
			action: 'stopGame',
			fn: function (r) {
				$overlayGame.hide();
				$roundResult.show();
				clearInterval(countdown);
				disablePaint();
				disableChat();
				App.ui.setTitle(Localization.GameOver);
				if (r.win) {
					$('#stopGameMessage').html(Localization.GameOverWinMessage);
					$('#gameNow').text(Localization.NewGameWinButton);
				} else {
					$('#stopGameMessage').html(Localization.GameOverMessage);
					$('#gameNow').text(Localization.NewGameButton);
				}
				$('#gameNow').click(function () {
					restarsRoomFind();
				});
				$("#stopGameOverlay").show();
			}
		});

		App.signalr.client({
			hub: 'gameHub',
			action: 'draw',
			fn: function (data) {
				var actions = JSON.parse(data);
				paintInst.actions = $.merge(paintInst.actions, actions);
				if (!paintInst.drawing) {
					paintInst.setData();
				}
			}
		});

		App.sendDraw = function (data) {
			App.signalr.server({
				hub: 'gameHub',
				action: 'draw',
				data: JSON.stringify(data)
			}).fail(function (e) {
				console.log('game.page.js', e);
			});
		};

		paintInst.onsendactions = function () {
			if (paintInst.actions != []) {
				App.sendDraw(paintInst.actions);
				paintInst.actions = [];
			}
		};

		function setCursor(el, pos) {
			var node = (typeof el == "string" || el instanceof String) ? document.getElementById(el) : el;
			if (!node) {
				return false;
			} else if (node.createTextRange) {
				var textRange = node.createTextRange();
				textRange.collapse(true);
				textRange.moveEnd(pos);
				textRange.moveStart(pos);
				textRange.select();
				return true;
			} else if (node.setSelectionRange) {
				node.setSelectionRange(pos, pos);
				return true;
			}
			return false;
		}

		App.signalr.client({
			hub: 'gameHub',
			action: 'newMessage',
			fn: function (r) {
				$chat.append('<li class="message" style="background-color: {color};"><b><span class="name-click">{name}</span>:</b> {msg}</li>'
					.replace('{color}', r.color).replace('{name}', r.name).replace('{msg}', r.msg));
				var $msg = $chat.find('li:last');

				$chat.height() < $chatparent.height() ? $chatparent.css('overflow-y', 'hidden') : $chatparent.css('overflow-y', 'auto');

				TweenMax.set($msg, { y: -10 });
				TweenMax.to($msg, 1, { y: 0, ease: Elastic.easeOut });
				TweenMax.to($chat.parent(), 1, { scrollTop: $chat.height() });

				$('.name-click').unbind('click').click(function () {
					$message.val($message.val() + ' ' + $(this).text() + ', ').focus();
					setCursor($message.get(0), $message.val().length);
				});
			}
		});

		App.signalr.client({
			hub: 'gameHub',
			action: 'userGotOut',
			fn: function (u) {
				App.alert.info(Localization.UserGotOut.replace('{name}', u.name));
			}
		});

		App.signalr.client({
			hub: 'gameHub',
			action: 'roomClosed',
			fn: function () {
				App.alert.info(Localization.RoomIsEmptyMessage);
				clearInterval(countdown);
				App.ui.setTitle(Localization.GameTitle);
				App.goToPage('intro');
			}
		});

		function restarsRoomFind() {
			disableChat();
			resetPaint();
			disablePaint();
			clearInterval(countdown);
			$("#stopGameOverlay").hide();
			$('#chooseWordOverlay').hide();
			$cancasOvelray.hide();
			$imageulr.hide().attr('href', '');
			$imageulrInput.hide().val('');
			$chat.empty();
			$userList.empty();

			App.signalr.server({
				hub: 'gameHub',
				action: 'findRoom'
			}).fail(function (e) {
				console.log('game.page.js', e);
			});

			$overlayGame.show();
		}

		App.signalr.server({
			hub: 'gameHub',
			action: 'findRoom'
		}).fail(function (e) {
			console.log('game.page.js', e);
		});
	}
});